
const through = require('through2')
var gutil = require('gulp-util');
var PluginError = gutil.PluginError
const PLUGIN_NAME = 'gulp-prefixer'
var marked = require('marked')
var fs = require('fs')

function markdownToHtml (tpl, md, op) {
  let markdownHtml = marked(md, op)
  let html = ''
  if (tpl === '') {
    html = markdownHtml
  } else {
    // 替换 {{ markdown }}
    html = tpl.replace(/\{\{\W*markdown\W*\}\}/ig, markdownHtml)
  }
  return new Buffer(html)
}

function plugin(tplPath, op) {
  var options = op || {}
  let templatePath = ''
  if (typeof tplPath === 'object') {
    options = tplPath
  }
  if (typeof tplPath === 'string') {
    templatePath = tplPath
  }

  // throw new PluginError(PLUGIN_NAME, 'Missing prefix text!');
  var template = ''
  if (templatePath !== '') {
    template = String(fs.readFileSync(templatePath))
  }

  function bufferContent (file, enc, cb) {
    // console.log('bufferContent')
    // console.log(file.isBuffer(), file.isStream())
    if (file.isBuffer()) {
      file.contents = markdownToHtml(template, String(file.contents), options)
      file.path = file.path.replace(/\.md/i, '.html')
    }
    this.push(file)
    // cb(null, file)
    cb()
  }
  function endBuffer () {
    // console.log('endBuffer')
  }
  return through.obj(bufferContent, endBuffer)
}

module.exports = plugin
